<template>
  <div>
    <Row>
      <Card>
        <p slot="title">
          <Icon type="navicon-round"></Icon>
          晨检机APK管理
        </p>
        <VmBtable type="edit" ref="VmBtable"
                  :columns="dataColumns"
                  :data="dataTable"
                  :searchparam="searchParam"
                  :exportBtn="false"
                  :importBtn="false"
                  :batchDelBtn="false"
                  :downTemplate="false"
                  :isControl="loginType === 'platform'"
                  v-on:searchFn="searchFn"
                  v-on:page-change="pageChangeFn"
                  v-on:addFn="addFn"
                  v-on:editFn="editFn"
                  v-on:deleteFn="deleteFn"
                  :operate="operate"
                  placeholder="APK名关键字"
                  searchText="APK名："
                  cleanText="刷新"
                  exportPath="exportPath"
                  v-on:restFn="restFn">
          <div slot="search" class="db_inline">
            版本号：
            <Input v-model="searchParam.version" placeholder="版本号" style="width: 180px;"/>
          </div>
        </VmBtable>
      </Card>
    </Row>
    <Modal v-model="modal.visible" :title="modal.title" v-on:on-ok="subForm" :mask-closable="false" width="540"
           v-on:on-cancel="cancelSub">
      <Form ref="Form" :model="modal.form" :label-width="100" label-position="right" :rules="modal.rules">
        <FormItem label="名称" prop="name">
          <Input v-model="modal.form.name" placeholder="输入APK名称" style="width:83%"/>
        </FormItem>
        <FormItem label="APK版本" prop="version">
          <Input v-model="modal.form.version" placeholder="输入APK版本" style="width:83%"/>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="modal.form.remark" type="textarea" placeholder="备注" style="width:83%"/>
        </FormItem>
        <Upload
          type="drag"
          accept=".apk"
          :default-file-list="modal.form.uploadList"
          :headers="headers"
          :before-upload="beforeUpload"
          :on-remove="removeFile"
          :on-success="uploadSuccess"
          :action="action">
          <div style="padding: 20px 0">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>选择APK</p>
          </div>
        </Upload>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modal.visible=false">取消</Button>
        <Button type="primary" @click="subForm" :loading="modal.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="device.visible" :title="device.title" :mask-closable="false" width="70%">
      <div>名称搜索：
        <Input v-model="device.search.deviceName" icon="search" @on-change="queryTerminal" placeholder="设备名关键字"
               style="width: 180px;"/>
      </div>
      <div style="margin-top: 20px">
        <Table ref="terminal" :columns="device.equColumns"
               :data="device.equData"
               @on-selection-change="selectChange"
               height="500"/>
      </div>
      <Row type="flex" justify="end" class="footer">
        <div class="margin-top-10">
          <span>总共 {{device.search.total}} 条记录 &nbsp;</span>
          <Page class="db_inline" :total="device.search.total" :current="device.search.current"
                :page-size="device.search.size"
                @on-change="terminalPageChange" show-elevator></Page>
        </div>
      </Row>
      <div slot="footer">
        <Button type="text" @click="device.visible=false">取消</Button>
        <Button type="primary" @click="sureUpdateFn" :loading="modal.loading">升级选中</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import API from "@/api/api";
  import VmBtable from "@/components/vm/vm-btable";
  import Cookie from "js-cookie"
  import Axios from 'axios'

  export default {
    components: {
      VmBtable
    },
    data() {
      return {
        loginType: Cookie.getJSON('loginType'),
        searchParam: {
          current: 1,
          size: 20,
          total: 0,
          name: '',
          version: '',
        },
        exportPath: Cookie.getJSON('cdnUrl'),
        action: Axios.defaults.baseURL + '/cos/upload',
        headers: {
          Authorization: "Bearer " + Cookie.getJSON('TOKEN'),
        },
        dataColumns: [
          {
            title: '序号',
            type: 'index',
            align: 'center',
            width: 100
          },
          {
            title: '名称',
            align: 'center',
            key: 'name',
          },
          {
            title: '版本号',
            align: 'center',
            key: 'version',
          },
          {
            title: '上传时间',
            align: 'center',
            key: 'createTime',
          },
          {
            title: '状态',
            align: 'center',
            key: 'status',
            render: (h, param) => {
              let status = param.row.status;
              if (status) {
                return h('div', {style: {color: 'green'}}, '上架')
              } else {
                return h('div', {style: {color: 'gray'}}, '下架')
              }
            }
          },

          {
            title: '操作',
            align: 'center',
            minWidth: 140,
            render: (h, params) => {
              let btn = [];
              let detailBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editFn(params.row)
                  }
                }
              }, '编辑');
              let delBtn = h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteFn(params.row)
                  }
                }
              }, '删除');
              let updateBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.updateFn(params.row)
                  }
                }
              }, '升级设备');
              let upBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.changeStatus(params.row)
                  }
                }
              }, '上架');
              let downBtn = h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.changeStatus(params.row)
                  }
                }
              }, '下架');
              let status = params.row.status;
              if (status) {
                btn = [detailBtn, downBtn, updateBtn, delBtn]
              } else {
                btn = [detailBtn, upBtn, updateBtn, delBtn]
              }
              if (this.loginType !== 'platform') {
                btn = [updateBtn]
              }
              return h('div', btn);
            }
          }
        ],
        operate: [],
        dataTable: [],
        modal: {
          visible: false,
          title: '',
          isEdit: false,
          loading: false,
          form: {
            name: '',
            version: '',
            key: '',
            fileName: '',
            uploadList: [],
            remark: '',
          },
          rules: {
            'name': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }], 'version': [{
              required: true,
              trigger: 'blur',
              message: '必填项'
            }]
          }
        },
        device: {
          visible: false,
          title: '',
          equColumns: [
            {
              type: 'index',
              title: '序号',
              align: 'center',
              minWidth: 40
            },
            {
              title: '设备名',
              key: 'deviceName',
              minWidth: 160,
              align: 'center'
            },
            {
              title: 'mac地址',
              key: 'mac',
              minWidth: 160,
              align: 'center'
            },
            {
              title: '软件版本',
              key: 'softwareVersion',
              minWidth: 200,
              align: 'center',
            },
            {
              title: '创建时间',
              key: 'createTime',
              minWidth: 150,
              align: 'center',
            },
            {
              type: 'selection',
              title: '全选',
              align: 'center',
              minWidth: 20
            },
          ],
          equData: [],
          search: {
            current: 1,
            size: 20,
            deviceName: '',
            total: 0
          },
          form: {
            apkId: '',
            array: []
          }
        }
      };
    },
    methods: {
      changeStatus(data) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否下架/下架该APK？',
          onOk: () => {
            API.changeStatus(data).then(resp => {
              this.queryFn();
            })
          }, onCancel: () => {

          }
        });
      },
      addFn() {
        Object.assign(this.modal, {
          visible: true,
          isEdit: false,
          title: '添加',
          form: {}
        })
      },
      editFn(data) {
        Object.assign(this.modal, {
          visible: true,
          isEdit: true,
          title: '编辑',
          form: data
        })
        this.modal.form.uploadList = [{name: data.fileName, url: ''}];
      },
      deleteFn(data) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该APK？',
          onOk: () => {
            API.deleteApk({id: data.id}).then(resp => {
              this.queryFn();
            })
          },
          onCancel() {
          }
        })
      },
      updateFn(data) {
        this.device.visible = true;
        this.device.title = '升级设备APK（版本号：' + data.version + '）';
        this.device.form.apkId = data.id;
        this.queryTerminal();
      },
      queryTerminal() {
        API.fetchDevice(this.device.search).then(resp => {
          let records = resp.data.records;
          for (let i in records) {
            if (this.device.form.array.lastIndexOf(records[i].id) !== -1) {
              records[i]._checked = true;
            }
          }
          this.device.equData = records;
          this.device.search.total = resp.data.total;
          this.device.search.current = resp.data.current;
        })
      },
      selectChange(array) {
        this.device.form.array = array.map(d => d.id);
      },
      terminalPageChange(current) {
        this.device.search.current = current;
        this.queryTerminal();
      },
      sureUpdateFn() {
        this.$Modal.confirm({
          title: '提示',
          content: '升级需要时间比较长，请耐心等待，是否继续？',
          onOk: () => {
            API.updateDeviceApk(this.device.form).then(resp => {
              this.$Notice.success({
                title: '提示',
                desc: '命令下发成功,请等待设备自动升级',
              })
              this.device.visible = false;
            })
          },
          onCancel: () => {
          }
        })
      },
      beforeUpload() {
        let key = this.modal.form.key;
        if (key) {
          this.$Notice.warning({
            title: '提示',
            desc: '请先删除已上传的APK'
          })
          return false;
        }
        this.$Spin.show();
      },
      removeFile() {
        let key = this.modal.form.key;
        if (key) {
          API.deleteFromTencent({fileName: key}).then(resp => {
            this.modal.form.key = '';
            this.modal.form.fileName = '';
          });
        }
      },
      uploadSuccess(res, file, fileList) {
        this.modal.form.key = res.data.key;
        this.modal.form.fileName = res.data.fileName;
        this.$Spin.hide();
      },
      restFn() {
        this.searchParam.current = 1;
        this.searchParam.size = 20;
        this.searchParam.name = '';
        this.searchParam.version = '';
        this.queryFn();
      },
      queryFn() {
        API.fetchApk(this.searchParam).then(
          res => {
            let data = res.data;
            this.dataTable = data.records;
            this.searchParam.total = data.total;
          },
          error => {
            this.$Message.info(error.msg);
          }
        );
      },
      complete() {
        Object.assign(this.modal, {
          visible: false,
          title: '',
          loading: false,
        });
        this.$refs.Form.resetFields();
      },
      subForm() {
        this.$refs.Form.validate(valid => {
          if (valid) {
            let data = Object.assign(this.modal.form);
            if (!data.key) {
              this.$Notice.error({
                title: '错误',
                desc: '请上传APK'
              })
              return;
            }
            if (data.id) {
              API.updateApk(data).then(resp => {
                this.queryFn();
                this.complete();
              })
            } else {
              API.createApk(data).then(resp => {
                this.queryFn();
                this.complete();
              })
            }
          }
        })
      },
      cancelSub() {

      },
      pageChangeFn(current) {
        this.searchParam.current = current;
        this.queryFn();
      },
      searchFn(value) {
        this.searchParam.name = value;
        this.queryFn();
      },
    },
    created() {
    },
    mounted() {
      this.queryFn();
    }
  }
</script>

<style scoped>

</style>
